var ue;

//页面加载完毕
$(function () {
    getDataByIdInShopEdit(root + 'cms/shop/findShopById', "#shopTmpl", "#shopContent");
    $("#saveOrupdate").click(function () {
        saveDataByInShopEdit(root + 'cms/shop/saveShop', 'shopList.jsp');
    });

    //定义变量，判断是新增还是修改,0是新增,1是修改
    var isModifyType = 0;

    //添加上传图片组件
    addShopImgComps();
    //上传图片
    upload("shop");

    //规格添加
    standard_deal();
});

function standard_deal() {
    //规格属性确定
    $('#standard_update').click(function () {
        $('#standard_Form').isValid(function (result) {
            if (result) {
                var _content = "<tr><td><input ckId='" + $('#add_standard').val() + "' class='ckSelect' type='checkbox' ckType='add' /></td>";
                _content += "<td>" + $('#standardName').val() + "</td><td>" + $('#standardValues').val() + "</td></tr>";
                if (isModifyType == 1) {//修改
                    var _this = $(".ckSelect:checked");
                    var _td = $(_this).parents('tr').find('td');
                    $(_td).eq(1).html($('#standardName').val());
                    $(_td).eq(2).html($('#standardValues').val());
                    $(_this).attr('checked', false);
                    $('#_selectAll').attr('checked', false);
                } else {//添加
                    $('#shopContent').find('#standard_content').append(_content);
                    $('#shopContent').find('#_selectAll').prop('checked', false);
                }
                $('#standard_Modal').modal('hide');
            }
        });
    });

    //编辑属性
    $('#shopContent').on('click', '.edit_img', function () {
        var updateArray = [];
        $(".ckSelect").each(function () {
            var check = $(this).is(':checked');
            if (check) {
                var _id = $(this).attr("ckId");
                updateArray.push(_id);
            }
        });
        if (updateArray.length == 0) {
            myAlert("请选择要编辑的项");
            return;
        }
        if (updateArray.length > 1) {
            myAlert("每次只能编辑一项");
            return;
        }
        var _this = $(".ckSelect:checked");
        var _td = $(_this).parents('tr').find('td');

        $('#add_standard').val($(_this).attr('ckId'));
        $('#standardName').val($(_td).eq(1).html());
        $('#standardValues').val($(_td).eq(2).html());

        isModifyType = 1;
        $('#standard_Modal').modal();
    });

    //删除属性
    $('#shopContent').on('click', '.delete_img', function () {
        var deleteArray = [];
        $(".ckSelect").each(function () {
            var check = $(this).is(':checked');
            if (check) {
                var _id = $(this).attr("ckId");
                deleteArray.push(_id);
            }
        });
        if (deleteArray.length == 0) {
            myAlert("请选择要删除的项");
            return;
        }
        myConfirm("确定要删除选中规格吗？", function () {
            $(".ckSelect:checked").each(function () {
                $(this).parents('tr').remove();
            });
            if ($('#standard_content').find('.ckSelect').length == 0) {
                $('#_selectAll').attr('checked', false);
            }
        });
    });

    //多选框全选与全否效果
    $('#shopContent').on('change', '#_selectAll', function () {
        $('#shopContent').find('.ckSelect').prop('checked', $(this).prop('checked'));
    });
    $('#shopContent').on('click', '.ckSelect', function () {
        $('#shopContent').find('#_selectAll').prop('checked', $('#shopContent').find('.ckSelect').length == $('#shopContent').find('.ckSelect').filter(':checked').length);
    });

}


function addShopImgComps() {
    //定义变量，判断是新增还是修改,0是新增,1是修改
    //添加图片
    $('#shopContent').on('click', '.add_img', function () {
        var num = $(this).parent().find('.upload_div').length;
        var type = Number($(this).attr('data-type'));

        if (type == 0) {
            num += 1;
            var ht = '<div class="upload_div" style="float: left; margin-right: 15px;"><img id="myImageShow' + num + '" src="" width="100px" height="100px"/><input type="hidden" id="imgUrl' + num + '" name="imgUrl" value=""/><input type="file" id="uploadPhotoFile' + num + '" name="photoFile" class="upload_file" data-type="' + type + '"/></div>';
            $(this).before(ht);
            if ($(this).parent().find('.upload_div').length >= 6) {
                $(this).hide();
            }
        } else if (type == 1) {
            $('#add_standard').val('');
            $('#standardName').val('');
            $('#standardValues').val('');
            isModifyType = 0;
            $('#standard_Modal').modal();
        }
        //doc 结构改变了，要重新注册事件
        //上传图片
        upload("shop");
    });

    //删除照片
    $('#shopContent').on('click', '.del_img', function () {
        //第三张图消失
        $('.col-md-5 div').last().remove();
        //加号出来
        $('.add_img').show();
        if ($('.col-md-5 div').length == 0) {
            //减号消失
            $('.jian_img').css('display', 'none');
        }
    });
}

//获取商品分类
function getShopCategories(objid) {
    $.ajax({
        url: root + "cms/category/findShopCategoryNEStatusPage",
        data: {
            nextPage: 0,
            pageSize: 99999,
            sortData: null,
            jsonFilter:"{'search_EQ_type':'1'}"
        },
        type: 'POST',
        timeout: 7000,
        dataType: 'json'
    }).done(function (data) {
        if (data.code == 1) {
            var _html = "<option value='' selected>请选择</option>";
            for (var i = 0; i < data.object.content.length; i++) {
                if (objid == data.object.content[i].id) {
                    _html += "<option value='" + data.object.content[i].id + "' selected>" + data.object.content[i].categoryName + "</option>";
                } else {
                    _html += "<option value='" + data.object.content[i].id + "'>" + data.object.content[i].categoryName + "</option>";
                }
            }
            $("#categoryType").html(_html);

            if (data.object.content <= 0) {
                //没有分类数据，提示去添加
                myConfirm("没有商品分类，无法添加商品，请先去添加？", function () {
                    location.href = "../category/categoryList.jsp";
                })
            }
        } else {
            myAlert(data.message || tipMessage.undefined_msg);
        }
    }).fail(function (jqXHR, textStatus, errorThrown) {
        if (textStatus == "timeout") {
            myAlert(tipMessage.timeout_msg);
        } else {
            myAlert(tipMessage.error_msg);
        }
    });
}

// 通过ID获取单条数据
function getDataByIdInShopEdit(url, tmpl, content) {
    var tId = getUrlParam("id");
    if (!tId) {
        myAlert('id参数不能为空');
        var contentHtml = $(tmpl).render("");
        $(content).html(contentHtml);
        getShopCategories();
        return;
    }
    $.ajax({
        url: url,
        type: 'post',
        dataType: 'json',
        data: {
            modelId: tId
        },
        success: function (data) {
            console.log(data);
            if (data.code == 1) {
                var contentHtml = $(tmpl).render(data.object);
                $(content).html(contentHtml);
                ue = UE.getEditor('shopProductIntroduce');
                ue.addListener("ready", function () {
                    // editor准备好之后才可以使用
                    ue.setContent(data.object.shopProductIntroduce);
                });
                getShopCategories(data.object.categoryType);

                //加载介绍图
                if (data.object.shopProductPicUrls) {
                    var desImg = "";
                    $.each(data.object.shopProductPicUrls.split(","), function (i) {
                        desImg += '<div class="upload_div" style="float: left; margin-right: 15px;"><img id="myImageShow' + (i + 1) + '" src="../../' + this + '" width="100px" height="100px" /><input type="hidden" id="imgUrl' + (i + 1) + '" name="imgUrl" value="' + this + '"/><input type="file" id="uploadPhotoFile' + (i + 1) + '" name="photoFile" class="upload_file" data-type="' + (i + 1) + '"></div>';
                    });
                    $(content).find('.add_img').eq(0).before(desImg);
                    if (data.object.shopProductPicUrls.split(",").length >= 6) {
                        $(content).find('.add_img').eq(0).hide();
                    }
                }

                //加载规格属性
                if (data.object.standards) {
                    var _standard = "";
                    $.each(data.object.standards, function (i) {
                        _standard += "<tr><td><input ckId='" + this.id + "' class='ckSelect' type='checkbox' ckType='update' /></td>";
                        _standard += "<td>" + this.shopStandsName + "</td><td>" + this.shopStandsValuesStr + "</td></tr>";
                    });
                    $(content).find('#standard_content').html(_standard);
                }
            } else {
                //异常
                var contentHtml = $(tmpl).render("");
                $(content).html(contentHtml);
                ue = UE.getEditor('shopProductIntroduce');
                ue.addListener("ready", function () {
                    // editor准备好之后才可以使用
                    ue.setContent("");
                });

                getShopCategories("");
            }
        }
    });
}

// 保存数据
function saveDataByInShopEdit(url, backUrl) {
    $('#submit_form').isValid(function (result) {
        if (!result) {
            myAlert("还有不符合规定的字段填写，请检查！");
            return;
        }
        //轮播图
        var _imgurls = [];
        $('#shopContent').find('#imgUrls_div').find('input[name="imgUrl"]').each(function () {
            _imgurls.push($(this).val());
        });
        if (_imgurls.length <= 0) {
            myAlert('商品图片不能为空');
            return;
        }
        //规格
        var _standards = [];
        $('#standard_table').find('#standard_content').find('tr').each(function () {
            var name = $(this).find('td')[1].textContent;
            var value = $(this).find('td')[2].textContent;
            if (name.length <= 0) {
                myAlert('规格名称不能为空');
                return;
            }
            if (name.indexOf(",") != -1 || name.indexOf("，") != -1
                || name.indexOf("；") != -1 || name.indexOf(";") != -1
                || name.indexOf("：") != -1 || name.indexOf(":") != -1) {
                myAlert('规格不能包含特殊字符');
                return;
            }
            if (value.length <= 0) {
                myAlert('规格取值不能为空');
                return;
            }
            //颜色:红色,蓝色,灰色,白色;尺寸:大号,中号,小号
            if (value.indexOf("；") != -1 || value.indexOf(";") != -1
                || value.indexOf("：") != -1 || value.indexOf(":") != -1) {
                myAlert('规格不能包含特殊字符');
                return;
            }
            var standard = name + ":" + value;
            _standards.push(standard);
        });
        if (_standards.length <= 0) {
            myAlert('商品规格不能为空');
            return;
        }
        $("#saveOrupdate").addClass('disable_btn');
        $.ajax({
            url: url,
            type: "POST",
            timeout: 7000,
            data: {
                shopId: $("#shopId").val(),
                shopProductName: $("#shopProductName").val(),//商品名称
                originalPrice: $("#originalPrice").val(),//商品原价
                shopProductPrice: $("#shopProductPrice").val(),//商品价格
                shopProductBrief: $("#shopProductBrief").val(),//商品简介（产品参数）
                discountRate: $("#discountRate").val(),//折扣比例
                shopProductPicUrls: _imgurls.toString(),//商品图片（banner）URL，多张逗号分割
                shopProductIntroduce: ue.getContent(),//商品介绍
                categoryType: $("#categoryType").val(),//商品分类 long
                standards: _standards.join(";"),//商品规格,字段名:standards,格式\"颜色:红色,蓝色,灰色,白色;尺寸:大号,中号,小号"
                shopProductInventory: $("#shopProductInventory").val(),//库存 long
                brand: $("#brand").val(),//品牌 brand,eg:e孝道官网,苏宁,苏泊尔
                sort: $("#sort").val()//排序值
            },
            success: function (data) {
                if (data.code == 1) {
                    backAction(backUrl);
                } else {
                    $("#saveOrupdate").removeClass('disable_btn');
                    myAlert(data.message || '数据加载失败，稍后重试！');
                }
            },
            error: function () {
                $("#saveOrupdate").removeClass('disable_btn');
            }
        });
    });
}
